<?php

namespace App\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use common\utils\SysCode;
use App\Exceptions\CustomException;
use Illuminate\Support\Facades\DB;

class ResponseMiddleware
{
    // 统一数据格式
    public function handle(Request $request, Closure $next)
    {
        if (env('APP_DEBUG') == true) {
            DB::enableQueryLog();
        }
        $headers = $this->headers($request);
        // 跨域处理
        if ($request->method() === 'OPTIONS') {
            return response("", 204, $headers);
        }
        $response = $next($request)->withHeaders($headers);
        // 自定义错误
        if ($response->exception instanceof CustomException) {
            return $response;
        }
        $status = $response->status();
        $content = $response->getOriginalContent();
        switch ($status) {
            case Response::HTTP_OK://200
                $response->setContent(output($content));
                break;
            case SysCode::UNAUTHORIZED://401
            case SysCode::FORBIDDEN://403
            case SysCode::NOT_FOUND://404
                $response->setContent(output('', $status));
                break;
            case Response::HTTP_METHOD_NOT_ALLOWED://405
                $response->setContent(output('', SysCode::NOT_FOUND))->setStatusCode(SysCode::NOT_FOUND);
                break;
            case Response::HTTP_UNPROCESSABLE_ENTITY://422
                $response->setContent(output($content, SysCode::INVALID_ARGUMENT));
                break;
        }
        return $response;
    }

    public function headers(Request $request)
    {
        $headers = [
            'Allow' => 'GET, PUT, PATCH, DELETE, HEAD, OPTIONS',
            'Access-Control-Allow-Origin' => $request->server->get('HTTP_ORIGIN'),
            'Access-Control-Allow-Methods' => 'GET, PUT, PATCH, DELETE, HEAD, OPTIONS',
            'Access-Control-Allow-Headers' => 'Authorization, Content-Type',
        ];
        return $headers;
    }
}
